from flask import Blueprint, request, jsonify
from extensions import db
from models import *

api = Blueprint('api', __name__, url_prefix='/api')

# ---------- 员工 CRUD ----------
@api.route('/employees', methods=['POST'])
def create_employee():
    data = request.get_json()
    emp = EmployeeBasicInfo(**data)
    db.session.add(emp)
    db.session.commit()
    return jsonify({'message': 'Employee created'}), 201

@api.route('/employees', methods=['GET'])
def list_employees():
    emps = EmployeeBasicInfo.query.all()
    return jsonify([{c.name: str(getattr(e, c.name)) for c in e.__table__.columns} for e in emps])

@api.route('/employees/<employee_id>', methods=['GET'])
def get_employee(employee_id):
    e = EmployeeBasicInfo.query.get_or_404(employee_id)
    return jsonify({c.name: str(getattr(e, c.name)) for c in e.__table__.columns})

@api.route('/employees/<employee_id>', methods=['PUT'])
def update_employee(employee_id):
    e = EmployeeBasicInfo.query.get_or_404(employee_id)
    data = request.get_json()
    for k, v in data.items():
        setattr(e, k, v)
    db.session.commit()
    return jsonify({'message': 'Employee updated'})

@api.route('/employees/<employee_id>', methods=['DELETE'])
def delete_employee(employee_id):
    e = EmployeeBasicInfo.query.get_or_404(employee_id)
    db.session.delete(e)
    db.session.commit()
    return jsonify({'message': 'Employee deleted'})

# ---------- 示例：子表路由（培训记录） ----------
@api.route('/employees/<employee_id>/training', methods=['POST'])
def add_training(employee_id):
    data = request.get_json()
    tr = TrainingRecord(employee_id=employee_id, **data)
    db.session.add(tr)
    db.session.commit()
    return jsonify({'message': 'Training record added'}), 201

@api.route('/employees/<employee_id>/training', methods=['GET'])
def list_training(employee_id):
    records = TrainingRecord.query.filter_by(employee_id=employee_id).all()
    return jsonify([{c.name: str(getattr(r, c.name)) for c in r.__table__.columns} for r in records])